package ru.lukyanets.transmission.client.ui.controller;

import com.google.inject.Inject;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.SplitMenuButton;
import ru.lukyanets.transmission.client.action.AddTorrentFileAction;
import ru.lukyanets.transmission.client.action.AddTorrentUrlAction;
import ru.lukyanets.transmission.client.action.ConnectAction;
import ru.lukyanets.transmission.client.action.EditConnectionsAction;
import ru.lukyanets.transmission.client.config.ConnectionConfig;
import ru.lukyanets.transmission.client.connection.ConnectionInfo;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import static ru.lukyanets.transmission.client.util.LocalizationUtil.getString;

/**
 * @author slukyanets
 * @noinspection unused
 */
public class MainToolbarController implements Initializable {
    @FXML
    private Button open;
    @FXML
    private Button openUrl;
    @FXML
    private SplitMenuButton connection;

    @Inject
    private AddTorrentFileAction addTorrentFileAction;
    @Inject
    private AddTorrentUrlAction addTorrentUrlAction;
    @Inject
    private ConnectAction connectAction;
    @Inject
    private EditConnectionsAction editConnectionsAction;

    @Inject
    ConnectionConfig config;

    private final MenuItem manageConnections = new MenuItem(getString("toolbar.connection.manage"));

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        addTorrentFileAction.configure(open);
        addTorrentUrlAction.configure(openUrl);
        connectAction.configure(connection);

        fillMenu(config.getConnections());

        config.getConnectionsProperty().addListener((o, oldV, newV) -> fillMenu(newV));
        config.getDefaultConnectionProperty().addListener((o, oldV, newV) -> fillMenu(config.getConnections()));
    }

    private void fillMenu(List<ConnectionInfo> connections) {
        connection.getItems().clear();
        connections.forEach(c -> {
            MenuItem item = new MenuItem(c.getName());
            item.setUserData(c);
            connectAction.configure(item);
            if (c.equals(config.getDefaultConnection())) {
                item.getStyleClass().add("selected");
            }
            connection.getItems().add(item);
        });

        editConnectionsAction.configure(manageConnections);
        connection.getItems().addAll(new SeparatorMenuItem(), manageConnections);
    }
}
